import { reqAddCart,reqBatchCheckCart,reqBatchDeleteCart,reqCartList, reqCheckedCart, reqDeleteCart } from "@/api";

const state = {
  cartList: [],

};

const mutations = {
  SET_CARTLIST(state, cartList) {
    state.cartList =cartList
  }
};

const actions = {
  //删除选中商品
  async batchDeleteSel({commit}, skuIdList) {
    try {
      let result = await reqBatchDeleteCart(skuIdList)  
      if (result && result.code == 200) {
        return 'ok'
      }
      return Promise.reject(result.message || '批量删除失败')
    } catch (error) {
      return Promise.reject(error)
    }
  },
  //全选、全不选
  async batchCheckedAll({commit},{isChecked, skuIdList}) {
    try {
      let result = await reqBatchCheckCart(isChecked, skuIdList)
      if (result && result.code == 200) {
        return 'ok'
      }
      return Promise.reject(result.message || '选中失败')
    } catch (error) {
      return Promise.reject(error)
    }
  },
  //删除商品
  async deleteCart({ commit },skuId){
    try {
      let result = await reqDeleteCart(skuId)
      if (result && result.code == 200) {
        return
      }
      return Promise.reject(result.message || '删除失败')
    } catch (error) {
      return Promise.reject(error)
    } 
  },
  //商品选中状态
  async checkCart({ commit },{ skuId,isChecked }) {
    try {
      let result = await reqCheckedCart(skuId,isChecked)
      if (result  && result.code == 200) {
        return 'ntgc'
      }
      return Promise.reject(result.message || '选中状态')
    }  catch (error) {
      return Promise.reject(error)
    }
  },
  //购物车列表
  async getCartList({ commit }) {
    try {
      let result = await reqCartList()
      if (result && result.code == 200) {
        console.log('接口返回的数据', result);
        commit('SET_CARTLIST',result.data[0]?.cartInfoList || [])

      } else {
        console.error(error);
      }
    } catch (error) {
      console.error(error);
    }
  },
  //添加购物车(修改商品数量)
  async addCart({ commit },{ skuId,skuNum }) {

    try {
      let result = await reqAddCart(skuId, skuNum)
      if(result && result.code == 200) {
        return 'ok'
      } else {
        return Promise.reject('添加购物车失败')
      } 
    } catch (error) {
      return Promise.reject(error)
    }
  }
};

const getters = {};

export default {
namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
